<script setup>
import bootPopup from '@/components/bootPopup.vue';
import newLoading from '@/components/newLoading/index.vue';
import myTextarea from '../components/myTextarea.vue'
import Toast from '@vant/weapp/dist/toast/toast';
import { usePaintingStore, useAppStore } from '@/store';
import { imgUploadVerify } from '@/utils/auth'
import { getCategoryDetail } from '@/api/home'
import { editImgUpload, imgAiBackground, getImageByTaskId } from '@/api/painting'
import { ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'



const paintingStore = usePaintingStore()
const appStore = useAppStore()

// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 页面参数
const queryParams = ref({})
// 原始图片地址
const oldImageFileUrl = ref('')
// 提交数据
const queryData = ref({
    imgModel: 'img2img_e_commerce_style',
    model: 'DOUBAO',
    modelVersion: '12',
})
// 消耗算力
const expendNum = ref(0)
// 图片数量
const imgNumList = ref([])
// 绘图历史文案名称
const historyName = ref('bgRedrawingHistory')
// 绘图历史文案列表
const selectList = ref([])

const loading = ref(false);
const loadingRef = ref(null);

// 任务ID
const taskId = ref('')
let timer = null

// 引导层显示
const bootPopupShow = ref(false)


const placeholder = `（修饰词+）主体动作+场景描绘+辅助元素，示例：一位身着浅蓝色连衣裙的少女，漫步在沙滩上。她的裙摆随风飘动，与远处天边的云霞相呼应。整个画面以暖调为主，融入海浪、贝壳等元素，营造出浪漫、惬意的氛围，呈现悠然氛围。`



// 点击顶部navbar标题
function onClickTitle() {
    bootPopupShow.value = true
}


// 设置图片文件URL
function setImageFileUrl(url) {
    queryParams.value.imageFileUrl = url
}



// 前往图片处理
function imageProcessing() {
    const data = {
        imageFileUrl: oldImageFileUrl.value,
    }
    uni.navigateTo({
        url: `/newEditionDraw/imageProcessing/index?item=${JSON.stringify(data)}`
    })
}



// 前往指令生成
function toAiCreateFn() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
        const previousPage = pages[pages.length - 2];
        if (previousPage.route.includes('painting')) {
            const data = {
                id: appStore.filterHomeCategory(13),
                baseImageUrl: queryParams.value.imageFileUrl,
            }
            uni.navigateTo({
                url: `/newEditionDraw/imgCreateText/index?item=${JSON.stringify(data)}`
            })
        } else {
            uni.navigateBack()
        }
    }
}

// 点击历史选中项
function clickSelectItem(item) {
    queryData.value.prompt = item.text
}


// 清除选中项
function clearSelectItem(item) {
    selectList.value = selectList.value.filter(i => i.text !== item.text)
    uni.setStorageSync(historyName.value, selectList.value)
}


// 获取存储文案历史记录
function getHistoryContent() {
    selectList.value = uni.getStorageSync(historyName.value) || []
}




// 存储文案历史记录
function setHistoryContent() {
    const existingIndex = selectList.value.findIndex(i => i.text === queryData.value.prompt);
    if (existingIndex !== -1) {
        selectList.value.splice(existingIndex, 1);
    }
    selectList.value.unshift({
        text: queryData.value.prompt,
        time: new Date().getTime()
    })
    uni.setStorageSync(historyName.value, selectList.value)
}




// 开始生成
async function startFn() {
    clearInterval(timer);
    await verifyFn()
    loading.value = true
    await editImgUploadFn()
    imgAiBackgroundFn()
}

// 获取任务状态
async function getImageByTaskIdFn() {
    const res = await getImageByTaskId(taskId.value)
    if (res.data.state === 1) {
        clearInterval(timer);
        await loadingRef.value.completeLoading()
        res.data.title = queryInfo.value.title
        res.data.modelTypeId = queryItem.value.modelTypeId
        uni.navigateTo({
            url: `/newEditionDraw/bgRedrawing/detail/index?data=${JSON.stringify(res.data)}`
        })
    } else if (![3, 4].includes(res.data.state)) {
        clearInterval(timer);
        const errorMessage = res.data?.remark.split('失败原因：')[1]
        Toast.fail(errorMessage);
        loading.value = false
    }
}


// 发起生成背景任务
async function imgAiBackgroundFn() {
    try {
        const res = await imgAiBackground(queryData.value)
        paintingStore.setBgRedrawingFn(queryData.value)
        setHistoryContent()
        taskId.value = res.data.taskId
        timer = setInterval(() => {
            getImageByTaskIdFn()
        }, 5000);
    } catch (error) {
        loading.value = false
    }
}


// 上传原图
async function editImgUploadFn() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await editImgUpload({
                type: 12,
                orgImg: queryParams.value.imageFileUrl
            })
            queryData.value.imageFileUrl = res.orgImgUrl
            resolve()
        } catch (error) {
            loading.value = false
            reject()
        }
    })
}



// 上传图片
async function uplaodImgFn() {
    const res = await imgUploadVerify()
    queryParams.value.imageFileUrl = res
    oldImageFileUrl.value = res
}


// 校验方法
function verifyFn() {
    return new Promise((resolve, reject) => {
        if (!queryParams.value.imageFileUrl) {
            Toast.fail('请上传图片')
            return reject()
        } else if (!queryData.value.prompt) {
            Toast.fail('请输入描述词')
            return reject()
        }
        resolve()
    })
}


// 数据转换
function dataConversion() {
    queryInfo.value.categoryParam.forEach(item => {
        if (item.title === 'imgNum') {
            imgNumList.value = item.data[0].title.split(',')
            queryData.value.num = imgNumList.value[0]
        } else if (item.title === 'expendNum') {
            expendNum.value = item.data[0].title
        }
    })
}


// 获取分类详情
async function getCategoryDetailFn() {
    const res = await getCategoryDetail(queryItem.value.id)
    queryInfo.value = res.data
    dataConversion()
}


// 加载关闭事件
function loadingClose() {
    clearInterval(timer);
}

onUnload(() => {
    clearInterval(timer);
    loading.value = false
})


onLoad((e) => {
    if (e.item) {
        queryItem.value = JSON.parse(e.item)
        queryItem.value.prompt && (queryData.value.prompt = queryItem.value.prompt)
        queryItem.value.modelTypeId && (queryData.value.modelVersion = queryItem.value.modelTypeId)
        if (queryItem.value.imageFileUrl) {
            uni.getImageInfo({
                src: queryItem.value.imageFileUrl,
                success(res) {
                    queryParams.value.imageFileUrl = res.path
                    oldImageFileUrl.value = res.path
                }
            })
        }
    }
    getHistoryContent()
    getCategoryDetailFn()
})

defineExpose({
    setImageFileUrl,
})

const textAreaStyle = {
    height: "300rpx",
}

const labelStyle = {
    fontWeight: "bold",
}
</script>

<template>
    <div class='bgRedrawing'>
        <NavBar>{{ queryInfo?.title }}</NavBar>
        <div class="container">
            <div class="title_box">
                <div>上传图片</div>
                <div class="explain" @click="onClickTitle">
                    <i class="iconfont ai-icon-tishishuoming"></i>
                    玩法说明
                </div>
            </div>
            <div class="uploadImg" @click="uplaodImgFn">
                <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" mode="heightFix" class="imgSty" alt="">
                <div class="upload_btn" v-else>
                    <i class="iconfont ai-icon-shangchuancankaotu"></i>
                    <div class="text">上传图片</div>
                </div>

                <div class="imageProcessing_btn" v-if="queryParams.imageFileUrl" @click.stop="imageProcessing">
                    <div class="text">图片调整</div>
                </div>

                <div class="img_description" v-if="!queryParams.imageFileUrl">
                    擅长于所有类型的产品和人物背景生成，具有主体不变，画面位置随意调整，背景高度融合，场景真实，比例协调等强大功能。
                </div>
            </div>
            <div class="textarea_box">
                <myTextarea v-model="queryData.prompt" keyName="text" :selectList="selectList"
                    @clearSelectItem="clearSelectItem" @clickSelectItem="clickSelectItem" label="输入背景描述词"
                    lastLabel="(建议120字内)" :labelStyle="labelStyle" :textAreaStyle="textAreaStyle"
                    :placeholder="placeholder">
                </myTextarea>
                <div class="ai_create_btn" @click="toAiCreateFn">
                    AI生成
                    <i class="iconfont ai-icon-suiji"></i>
                </div>
            </div>

            <div class="title_box">选择生成张数</div>
            <div class="imgNumList">
                <div class="imgNum_item" :class="{ active: queryData.num === item }" v-for="item, index of imgNumList"
                    :key="index" @click="queryData.num = item">
                    {{ item }}
                </div>
            </div>


        </div>
        <div class="footer">
            <div class="footer_placeholder"></div>
            <div class="footer_content">
                <myDrawButton :expendNum="expendNum * queryData.num" @click="startFn"></myDrawButton>
            </div>
        </div>
    </div>
    <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待10秒']" @close="loadingClose">
    </newLoading>
    <bootPopup v-model="bootPopupShow" :title="queryInfo?.title" type="12"></bootPopup>
    <van-toast id="van-toast" />
</template>

<style lang='scss' scoped>
.bgRedrawing {
    .container {
        padding: 0 30rpx;

        .title_box {
            position: relative;
            font-size: 28rpx;
            font-weight: bold;
            color: var(--a-one-text-color);
            padding-left: 30rpx;
            margin: 40rpx 0 18rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translate(0, -50%);
                width: 12rpx;
                height: 18rpx;
                background: var(--a-main-color);
                border-radius: 6rpx;
            }

            .text {
                font-size: 24rpx;
                font-weight: normal;
            }

            .explain {
                font-size: 24rpx;
                color: var(--a-two-text-color);
                font-weight: normal;
                display: flex;
                align-items: center;
                gap: 10rpx;

                .iconfont {
                    font-size: 24rpx;
                    color: var(--a-two-text-color);
                }
            }
        }

        .uploadImg {
            position: relative;
            box-sizing: border-box;
            height: 400rpx;
            background: var(--a-main-box-bg-color);
            border-radius: 20rpx;
            margin-top: 22rpx;
            padding: 16rpx 20rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;

            .imgSty {
                display: block;
                width: 100%;
                height: 100%;
                background-color: rgba($color: #FFF, $alpha: 0.2);
            }

            .upload_btn {
                text-align: center;

                .iconfont {
                    display: block;
                    font-size: 36rpx;
                    color: var(--a-main-color);
                }

                .text {
                    margin-top: 5rpx;
                    font-size: 32rpx;
                    color: var(--a-three-text-color);
                }

            }

            .imageProcessing_btn {
                position: absolute;
                right: 20rpx;
                bottom: 20rpx;
                width: 104rpx;
                height: 43rpx;
                background: #57547B;
                border-radius: 23rpx;
                border: 1rpx solid rgba(255, 255, 255, 0.6);
                font-size: 20rpx;
                color: var(--a-one-text-color);
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .img_description {
                box-sizing: border-box;
                position: absolute;
                width: 100%;
                height: 100%;
                padding: 20rpx 24rpx;
                color: #e2e1ec !important;
                font-size: 30rpx;
                opacity: 0.3;
            }

        }

        .textarea_box {
            position: relative;
            margin-top: 43rpx;

            .ai_create_btn {
                position: absolute;
                right: 16rpx;
                bottom: 16rpx;
                z-index: 2;
                width: 104rpx;
                height: 43rpx;
                background: #57547B;
                border-radius: 23rpx;
                font-size: 20rpx;
                color: var(--a-one-text-color);
                border: 1rpx solid rgba(255, 255, 255, 0.6);
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 5rpx;

                .iconfont {
                    font-size: 24rpx;
                }
            }
        }

        .imgNumList {
            margin-top: 22rpx;
            display: flex;
            align-items: center;
            gap: 18rpx;

            .imgNum_item {
                box-sizing: border-box;
                width: 84rpx;
                height: 84rpx;
                border-radius: 13rpx;
                color: var(--a-one-text-color);
                background: var(--a-main-box-bg-color);
                border: 4rpx solid transparent;
                display: flex;
                align-items: center;
                justify-content: center;

                &.active {
                    color: var(--a-main-color);
                    border: 4rpx solid var(--a-main-color);
                }
            }
        }



    }

    .footer {
        .footer_placeholder {
            height: 176rpx;
        }

        .footer_content {
            box-sizing: border-box;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 176rpx;
            background: var(--a-main-tabNav-bg-color);
            padding: 28rpx 30rpx 0;
        }
    }
}
</style>